import json

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()  # 创建谷歌浏览器的options对象来接收浏览器的相关设置

options.add_argument('--start-maximized')  # 最大化窗口
options.add_argument('--incognito')  # 无痕浏览
options.add_argument('--disable-extensions')  # 禁用浏览器的扩展程序,避免干扰网站的打开
options.add_experimental_option("detach", True)  # 禁止浏览器自动关闭
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)

# options.add_argument('--headless')
# options.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"',)
# options.add_argument('--disable-gpu')

driver = webdriver.Chrome(options)  # 创建谷歌浏览器驱动对象

driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    'source':'''
    Object.defineProperty(navigator, 'webdriver',{get:() => false})
    '''
})

driver.get('https://mnks.jxedt.com/ckm1/mnks/')

wait = WebDriverWait(driver, 6) #设置等待时间

li = driver.execute_script('return list')  #执行js代码返回网站中js里面的值   接收题目与答案
# print(li)

# with open('mnks.json','w',encoding='utf-8') as fp:
#     json.dump(li,fp,ensure_ascii=False,indent=4)    #将li以json格式写入到json文件中

#获取每道题目
for i in li:
    #判断题目是否加载出来
    name = i['qname'][:5]
    wait.until(EC.presence_of_element_located((By.XPATH, f'//p[contains(text(),"{name}")]')))   #等待 xpath模糊查询到题目    这里可以用slepp()替换
    answer = i['answer']
    wait.until(EC.presence_of_element_located((By.XPATH, f'//li[@anser="{answer}"]'))).click()   #等待 答案选项加载出来并且点击   这里可以用driver.find_elements((By.XPATH, f'//li[@anser="{answer}"]'))).click()替换

else:
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.jj-btn.xzjj'))).click()  #CSS样式选择器找到对应的元素  空格用.替换

# driver.quit()
